﻿<!DOCTYPE html>
<html>
<head>
    <title>JS Arrays Exercise 7</title>
    <link href="styles/js-console.css" rel="stylesheet" />
</head>
<body>
    <h1>Finds the index of given element in a sorted array of integers by using the binary search algorithm.</h1>
    <label for="arr-input">Array:</label>
    <input type="text" id="arr-input" />
    <label for="num-input">Number:</label>
    <input type="text" id="num-input" />
    <button onclick="execute()">Execute</button>
    <div id="js-console"></div>
    <script src="scripts/js-console.js"></script>
    <script>
        function execute()
        {
            var arr_string = jsConsole.read("#arr-input");
            var arr = arr_string.split(", ");
            var key = jsConsole.readInteger("#num-input");

            if (arr.length > 0)
            {
                var imin = 0;
                var imax = arr.length - 1;
                var imid = 0;
                var index_found = false;

                // continue searching while [imin,imax] is not empty
                while (imax >= imin)
                {
                    /* calculate the midpoint for roughly equal partition */
                    imid = Math.floor(imin + (imax - imin) / 2);
 
                    // determine which subarray to search
                    if (arr[imid] < key)
                    {
                        // change min index to search upper subarray
                        imin = imid + 1;
                    }
                    else if (arr[imid] > key)
                    {
                        // change max index to search lower subarray
                        imax = imid - 1;
                    }
                    else {
                        // key found at index imid
                        index_found = true;
                        break;
                    }
 
                }

                if (false == index_found)
                {
                    jsConsole.writeLine("Index not found");
                }
                else
                {
                    jsConsole.writeLine("Index of " + key + " is " + imid);
                }
            }
        }
    </script>
</body>
</html>
